﻿using System;
using System.Collections.Generic;

namespace Simhopp.Common
{
    /// <summary>
    /// Static class for generating common sql-querys
    /// </summary>
    static class GenerateSqlQuerys
    {
        /// <summary>
        /// Creates a sql update-query from a dictionary
        /// </summary>
        /// <param name="data">the dictionary</param>
        /// <param name="id">the name of the id-field to be used as index for the transaction</param>
        /// <returns></returns>
        public static string UpdateQuery(Dictionary<string, object> data, string id)
        {
            var keysAndValues = "";
            var index = "";
            int i = 0;
            foreach (var keyAndValue in data)
            {
                if (keyAndValue.Key == id)
                    index = String.Format("{0}='{1}'", keyAndValue.Key, keyAndValue.Value);
                else
                {
                    if (i++ != 0)
                        keysAndValues += ", ";
                    if (keyAndValue.Value == null)
                        keysAndValues += String.Format("{0}='{1}'", keyAndValue.Key, "");
                    else
                        keysAndValues += String.Format("{0}='{1}'", keyAndValue.Key, keyAndValue.Value.ToString().Trim());
                }
            }
            return string.Format("{0} where {1}", keysAndValues, index);
        }

        /// <summary>
        /// Creates a sql insert-query from a dictionary
        /// </summary>
        /// <param name="data">the dictionary</param>
        /// <param name="id">the name of the id-field which is used as an index in the table</param>
        /// <returns></returns>
        public static string InsertQuery(Dictionary<string, object> data, string id)
        {
            var keys = "";
            var values = "";
            int i = 0;
            foreach (var keysAndValues in data)
            {
                if (!keysAndValues.Key.Equals(id))
                {
                    if (i++ != 0)
                    {
                        keys += ", ";
                        values += ", ";
                    }
                    keys += String.Format("{0}", keysAndValues.Key);
                    values += String.Format("'{0}'", keysAndValues.Value);
                }
            }
            return String.Format("({0}) output Inserted.{1} values ({2})", keys, id, values);
        }


        internal static string DeleteQuery(Dictionary<string, object> data, string id)
        {
            return String.Format("where {0}='{1}'", id, data["Id"]);
        }
    }
}
